<template>
  <div class="advanced-search">
    <el-card>
      <template #header>
        <div class="search-header">
          <span class="search-title">
            <el-icon><Search /></el-icon>
            高级搜索
          </span>
          <div class="search-actions">
            <el-button size="small" @click="resetSearch">
              <el-icon><RefreshLeft /></el-icon>
              重置
            </el-button>
            <el-button size="small" @click="saveSearchTemplate" v-if="hasConditions">
              <el-icon><Collection /></el-icon>
              保存模板
            </el-button>
            <el-button 
              size="small" 
              :type="isExpanded ? 'warning' : 'primary'"
              @click="toggleExpanded"
            >
              <el-icon><component :is="isExpanded ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
              {{ isExpanded ? '收起' : '展开' }}
            </el-button>
          </div>
        </div>
      </template>

      <!-- 快速搜索栏 -->
      <div class="quick-search">
        <el-input
          v-model="quickSearchText"
          placeholder="快速搜索：输入关键词在所有字段中查找"
          size="large"
          clearable
          @clear="handleQuickSearch"
          @keyup.enter="handleQuickSearch"
        >
          <template #prepend>
            <el-select v-model="quickSearchField" placeholder="搜索字段" style="width: 120px;">
              <el-option label="全部字段" value="" />
              <el-option
                v-for="column in searchableColumns"
                :key="column.Field"
                :label="column.Field"
                :value="column.Field"
              />
            </el-select>
          </template>
          <template #append>
            <el-button @click="handleQuickSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>

      <!-- 高级搜索条件 -->
      <div v-show="isExpanded" class="advanced-conditions">
        <div class="conditions-container">
          <div 
            v-for="(condition, index) in searchConditions" 
            :key="index"
            class="condition-row"
          >
            <!-- 逻辑连接符 -->
            <div class="logic-operator" v-if="index > 0">
              <el-select v-model="condition.logic" style="width: 80px;" size="small">
                <el-option label="且" value="AND" />
                <el-option label="或" value="OR" />
              </el-select>
            </div>

            <!-- 字段选择 -->
            <div class="field-select">
              <el-select 
                v-model="condition.field" 
                placeholder="选择字段" 
                style="width: 140px;"
                size="small"
                @change="onFieldChange(condition, index)"
              >
                <el-option
                  v-for="column in searchableColumns"
                  :key="column.Field"
                  :label="column.Field"
                  :value="column.Field"
                />
              </el-select>
            </div>

            <!-- 操作符选择 -->
            <div class="operator-select">
              <el-select 
                v-model="condition.operator" 
                placeholder="操作符" 
                style="width: 100px;"
                size="small"
              >
                <el-option
                  v-for="op in getOperatorsForField(condition.field)"
                  :key="op.value"
                  :label="op.label"
                  :value="op.value"
                />
              </el-select>
            </div>

            <!-- 值输入 -->
            <div class="value-input">
              <!-- 文本输入 -->
              <el-input
                v-if="isTextInput(condition)"
                v-model="condition.value"
                placeholder="输入值"
                style="width: 160px;"
                size="small"
                clearable
              />

              <!-- 数字输入 -->
              <el-input-number
                v-else-if="isNumberInput(condition)"
                v-model="condition.value"
                style="width: 160px;"
                size="small"
                :precision="getNumberPrecision(condition.field)"
              />

              <!-- 日期选择 -->
              <el-date-picker
                v-else-if="isDateInput(condition)"
                v-model="condition.value"
                type="date"
                placeholder="选择日期"
                style="width: 160px;"
                size="small"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />

              <!-- 日期时间选择 -->
              <el-date-picker
                v-else-if="isDateTimeInput(condition)"
                v-model="condition.value"
                type="datetime"
                placeholder="选择日期时间"
                style="width: 180px;"
                size="small"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />

              <!-- 布尔选择 -->
              <el-select
                v-else-if="isBooleanInput(condition)"
                v-model="condition.value"
                placeholder="选择值"
                style="width: 160px;"
                size="small"
              >
                <el-option label="是" :value="true" />
                <el-option label="否" :value="false" />
              </el-select>

              <!-- 枚举选择 -->
              <el-select
                v-else-if="isEnumInput(condition)"
                v-model="condition.value"
                placeholder="选择值"
                style="width: 160px;"
                size="small"
              >
                <el-option
                  v-for="option in getEnumOptions(condition.field)"
                  :key="option"
                  :label="option"
                  :value="option"
                />
              </el-select>

              <!-- 范围输入 -->
              <div v-else-if="isRangeInput(condition)" class="range-inputs">
                <el-input-number
                  v-model="condition.value.min"
                  placeholder="最小值"
                  style="width: 75px;"
                  size="small"
                />
                <span class="range-separator">至</span>
                <el-input-number
                  v-model="condition.value.max"
                  placeholder="最大值"
                  style="width: 75px;"
                  size="small"
                />
              </div>
            </div>

            <!-- 删除条件按钮 -->
            <div class="condition-actions">
              <el-button 
                type="danger" 
                size="small" 
                @click="removeCondition(index)"
                :disabled="searchConditions.length === 1"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>

        <!-- 添加条件按钮 -->
        <div class="add-condition">
          <el-button type="primary" size="small" @click="addCondition">
            <el-icon><Plus /></el-icon>
            添加搜索条件
          </el-button>
        </div>

        <!-- 搜索模板 -->
        <div class="search-templates" v-if="searchTemplates.length > 0">
          <div class="template-title">搜索模板:</div>
          <div class="template-list">
            <el-tag
              v-for="template in searchTemplates"
              :key="template.id"
              class="template-tag"
              closable
              @click="loadSearchTemplate(template)"
              @close="deleteSearchTemplate(template.id)"
            >
              {{ template.name }}
            </el-tag>
          </div>
        </div>

        <!-- 搜索按钮 -->
        <div class="search-actions-bottom">
          <el-button type="primary" size="large" @click="executeSearch" :loading="searching">
            <el-icon><Search /></el-icon>
            执行搜索
          </el-button>
          <el-button size="large" @click="resetSearch">
            <el-icon><RefreshLeft /></el-icon>
            重置条件
          </el-button>
          <el-button 
            type="success" 
            size="large" 
            @click="exportSearchResults"
            :disabled="!hasResults"
          >
            <el-icon><Download /></el-icon>
            导出结果
          </el-button>
        </div>
      </div>

      <!-- 搜索历史 -->
      <div class="search-history" v-if="searchHistory.length > 0 && isExpanded">
        <div class="history-title">最近搜索:</div>
        <div class="history-list">
          <el-tag
            v-for="(history, index) in searchHistory.slice(0, 5)"
            :key="index"
            class="history-tag"
            @click="loadSearchHistory(history)"
          >
            {{ formatSearchHistory(history) }}
          </el-tag>
        </div>
      </div>
    </el-card>

    <!-- 搜索结果统计 -->
    <div class="search-results-info" v-if="hasSearched">
      <el-alert
        :title="`搜索完成，找到 ${searchResultCount} 条匹配记录`"
        type="success"
        :closable="false"
        show-icon
      >
        <template #default>
          <div class="result-summary">
            <span>搜索用时: {{ searchTime }}ms</span>
            <span v-if="activeConditions.length > 0">
              · 使用了 {{ activeConditions.length }} 个搜索条件
            </span>
          </div>
        </template>
      </el-alert>
    </div>

    <!-- 保存搜索模板对话框 -->
    <el-dialog
      v-model="showSaveTemplate"
      title="保存搜索模板"
      width="400px"
    >
      <el-form :model="templateForm" label-width="80px">
        <el-form-item label="模板名称">
          <el-input 
            v-model="templateForm.name" 
            placeholder="请输入模板名称"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="模板描述">
          <el-input 
            v-model="templateForm.description" 
            type="textarea"
            placeholder="可选：描述这个搜索模板的用途"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showSaveTemplate = false">取消</el-button>
        <el-button type="primary" @click="confirmSaveTemplate">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, RefreshLeft, Collection, ArrowUp, ArrowDown,
  Plus, Delete, Download 
} from '@element-plus/icons-vue'

const props = defineProps({
  columns: {
    type: Array,
    default: () => []
  },
  tableName: {
    type: String,
    required: true
  }
})

const emit = defineEmits(['search', 'export'])

const isExpanded = ref(false)
const searching = ref(false)
const hasSearched = ref(false)
const searchResultCount = ref(0)
const searchTime = ref(0)
const hasResults = ref(false)
const showSaveTemplate = ref(false)

// 快速搜索
const quickSearchText = ref('')
const quickSearchField = ref('')

// 搜索条件
const searchConditions = ref([createEmptyCondition()])

// 搜索模板
const searchTemplates = ref([])
const templateForm = reactive({
  name: '',
  description: ''
})

// 搜索历史
const searchHistory = ref([])

// 可搜索的列
const searchableColumns = computed(() => {
  return props.columns.filter(col => {
    const field = (col.Field || '').trim()
    const type = (col.Type || '').toUpperCase()
    return !['TEXT', 'LONGTEXT', 'BLOB', 'JSON'].some(t => type.includes(t)) &&
           field !== '所属区域' &&
           field !== '表类型' &&
           field !== 'id' 
  })
})


// 是否有搜索条件
const hasConditions = computed(() => {
  return searchConditions.value.some(condition => 
    condition.field && condition.operator && condition.value !== ''
  ) || quickSearchText.value.trim()
})

// 当前激活的搜索条件
const activeConditions = computed(() => {
  return searchConditions.value.filter(condition => 
    condition.field && condition.operator && condition.value !== ''
  )
})

// 创建空的搜索条件
function createEmptyCondition() {
  return {
    logic: 'AND',
    field: '',
    operator: '',
    value: ''
  }
}

// 添加搜索条件
const addCondition = () => {
  searchConditions.value.push(createEmptyCondition())
}

// 删除搜索条件
const removeCondition = (index) => {
  if (searchConditions.value.length > 1) {
    searchConditions.value.splice(index, 1)
  }
}

// 字段变化处理
const onFieldChange = (condition, index) => {
  condition.operator = ''
  condition.value = ''
  
  // 根据字段类型设置默认操作符
  const column = searchableColumns.value.find(col => col.Field === condition.field)
  if (column) {
    const operators = getOperatorsForField(condition.field)
    if (operators.length > 0) {
      condition.operator = operators[0].value
    }
  }
}

// 根据字段获取可用的操作符
const getOperatorsForField = (fieldName) => {
    if (!fieldName) {
    return [{ label:'请先选择字段', value:'nodata' }]
  }
  
  const column = searchableColumns.value.find(col => col.Field === fieldName)
  if (!column) return []
  
  const type = column.Type.toUpperCase()
  
  if (isNumberType(type)) {
    return [
      { label: '等于', value: '=' },
      { label: '不等于', value: '!=' },
      { label: '大于', value: '>' },
      { label: '大于等于', value: '>=' },
      { label: '小于', value: '<' },
      { label: '小于等于', value: '<=' },
      { label: '范围', value: 'BETWEEN' },
      { label: '为空', value: 'IS NULL' },
      { label: '不为空', value: 'IS NOT NULL' }
    ]
  }
  
  if (isDateType(type)) {
    return [
      { label: '等于', value: '=' },
      { label: '不等于', value: '!=' },
      { label: '晚于', value: '>' },
      { label: '晚于等于', value: '>=' },
      { label: '早于', value: '<' },
      { label: '早于等于', value: '<=' },
      { label: '范围', value: 'BETWEEN' },
      { label: '为空', value: 'IS NULL' },
      { label: '不为空', value: 'IS NOT NULL' }
    ]
  }
  
  if (isBooleanType(type)) {
    return [
      { label: '等于', value: '=' },
      { label: '不等于', value: '!=' }
    ]
  }
  
  // 文本类型
  return [
    { label: '等于', value: '=' },
    { label: '不等于', value: '!=' },
    { label: '包含', value: 'LIKE' },
    { label: '不包含', value: 'NOT LIKE' },
    { label: '开始于', value: 'STARTS_WITH' },
    { label: '结束于', value: 'ENDS_WITH' },
    { label: '为空', value: 'IS NULL' },
    { label: '不为空', value: 'IS NOT NULL' }
  ]
  
}

// 类型判断函数
const isNumberType = (type) => {
  return ['INT', 'BIGINT', 'DECIMAL', 'DOUBLE', 'FLOAT'].some(t => type.includes(t))
}

const isDateType = (type) => {
  return ['DATE', 'DATETIME', 'TIMESTAMP'].some(t => type.includes(t))
}

const isBooleanType = (type) => {
  return type.includes('TINYINT(1)') || type.includes('BOOLEAN')
}

const isEnumType = (type) => {
  return type.startsWith('ENUM')
}

// 输入类型判断
const isTextInput = (condition) => {
  if (!condition.field || !condition.operator) return true
  const column = searchableColumns.value.find(col => col.Field === condition.field)
  if (!column) return true
  
  const type = column.Type.toUpperCase()
  return !isNumberType(type) && !isDateType(type) && !isBooleanType(type) && 
         !isEnumType(type) && !isRangeInput(condition)
}

const isNumberInput = (condition) => {
  if (!condition.field || isRangeInput(condition)) return false
  const column = searchableColumns.value.find(col => col.Field === condition.field)
  return column && isNumberType(column.Type.toUpperCase())
}

const isDateInput = (condition) => {
  if (!condition.field || isRangeInput(condition)) return false
  const column = searchableColumns.value.find(col => col.Field === condition.field)
  return column && column.Type.toUpperCase().includes('DATE') && 
         !column.Type.toUpperCase().includes('DATETIME')
}

const isDateTimeInput = (condition) => {
  if (!condition.field || isRangeInput(condition)) return false
  const column = searchableColumns.value.find(col => col.Field === condition.field)
  return column && (column.Type.toUpperCase().includes('DATETIME') || 
                   column.Type.toUpperCase().includes('TIMESTAMP'))
}

const isBooleanInput = (condition) => {
  if (!condition.field || isRangeInput(condition)) return false
  const column = searchableColumns.value.find(col => col.Field === condition.field)
  return column && isBooleanType(column.Type.toUpperCase())
}

const isEnumInput = (condition) => {
  if (!condition.field || isRangeInput(condition)) return false
  const column = searchableColumns.value.find(col => col.Field === condition.field)
  return column && isEnumType(column.Type.toUpperCase())
}

const isRangeInput = (condition) => {
  return condition.operator === 'BETWEEN'
}

// 获取数字精度
const getNumberPrecision = (fieldName) => {
  const column = searchableColumns.value.find(col => col.Field === fieldName)
  if (!column) return 0
  
  const type = column.Type.toUpperCase()
  if (type.includes('DECIMAL')) {
    const match = type.match(/\(\d+,(\d+)\)/)
    return match ? parseInt(match[1]) : 2
  }
  return 0
}

// 获取枚举选项
const getEnumOptions = (fieldName) => {
  const column = searchableColumns.value.find(col => col.Field === fieldName)
  if (!column) return []
  
  const type = column.Type
  const match = type.match(/enum\((.*)\)/i)
  if (match) {
    return match[1].split(',').map(option => 
      option.trim().replace(/^'|'$/g, '')
    )
  }
  return []
}

// 切换展开状态
const toggleExpanded = () => {
  isExpanded.value = !isExpanded.value
}

// 快速搜索
const handleQuickSearch = () => {
  if (!quickSearchText.value.trim()) {
    resetSearch()
    return
  }
  
  const searchParams = {
    quickSearch: {
      text: quickSearchText.value.trim(),
      field: quickSearchField.value
    }
  }
  
  executeSearchWithParams(searchParams)
}

// 执行搜索
const executeSearch = () => {
  const searchParams = {
    conditions: activeConditions.value,
    quickSearch: quickSearchText.value.trim() ? {
      text: quickSearchText.value.trim(),
      field: quickSearchField.value
    } : null
  }
  
  executeSearchWithParams(searchParams)
}

// 执行搜索（带参数）
const executeSearchWithParams = (searchParams) => {
  searching.value = true
  const startTime = Date.now()
  
  // 添加到搜索历史
  if (searchParams.conditions?.length > 0 || searchParams.quickSearch) {
    addToSearchHistory(searchParams)
  }
  
  setTimeout(() => {
    emit('search', searchParams)
    searchTime.value = Date.now() - startTime
    hasSearched.value = true
    searching.value = false
    
    // 模拟搜索结果（实际应该从父组件传入）
    searchResultCount.value = Math.floor(Math.random() * 100)
    hasResults.value = searchResultCount.value > 0
  }, 300)
}

// 重置搜索
const resetSearch = () => {
  quickSearchText.value = ''
  quickSearchField.value = ''
  searchConditions.value = [createEmptyCondition()]
  hasSearched.value = false
  hasResults.value = false
  emit('search', { reset: true })
}

// 添加到搜索历史
const addToSearchHistory = (searchParams) => {
  const historyItem = {
    timestamp: Date.now(),
    params: JSON.parse(JSON.stringify(searchParams))
  }
  
  // 避免重复的搜索历史
  const exists = searchHistory.value.some(item => 
    JSON.stringify(item.params) === JSON.stringify(searchParams)
  )
  
  if (!exists) {
    searchHistory.value.unshift(historyItem)
    
    // 只保留最近20条历史
    if (searchHistory.value.length > 20) {
      searchHistory.value = searchHistory.value.slice(0, 20)
    }
    
    // 保存到localStorage
    localStorage.setItem(`search_history_${props.tableName}`, JSON.stringify(searchHistory.value))
  }
}

// 加载搜索历史
const loadSearchHistory = (historyItem) => {
  const params = historyItem.params
  
  if (params.quickSearch) {
    quickSearchText.value = params.quickSearch.text
    quickSearchField.value = params.quickSearch.field || ''
  }
  
  if (params.conditions && params.conditions.length > 0) {
    searchConditions.value = JSON.parse(JSON.stringify(params.conditions))
    isExpanded.value = true
  }
  
  executeSearchWithParams(params)
}

// 格式化搜索历史显示
const formatSearchHistory = (historyItem) => {
  const params = historyItem.params
  const parts = []
  
  if (params.quickSearch) {
    parts.push(`快速搜索: ${params.quickSearch.text}`)
  }
  
  if (params.conditions && params.conditions.length > 0) {
    parts.push(`${params.conditions.length}个条件`)
  }
  
  return parts.join(' + ') || '搜索'
}

// 保存搜索模板
const saveSearchTemplate = () => {
  templateForm.name = ''
  templateForm.description = ''
  showSaveTemplate.value = true
}

// 确认保存模板
const confirmSaveTemplate = () => {
  if (!templateForm.name.trim()) {
    ElMessage.warning('请输入模板名称')
    return
  }
  
  const template = {
    id: Date.now(),
    name: templateForm.name.trim(),
    description: templateForm.description.trim(),
    conditions: JSON.parse(JSON.stringify(activeConditions.value)),
    quickSearch: quickSearchText.value.trim() ? {
      text: quickSearchText.value.trim(),
      field: quickSearchField.value
    } : null,
    tableName: props.tableName,
    createTime: Date.now()
  }
  
  searchTemplates.value.push(template)
  
  // 保存到localStorage
  localStorage.setItem(`search_templates_${props.tableName}`, JSON.stringify(searchTemplates.value))
  
  ElMessage.success('搜索模板保存成功')
  showSaveTemplate.value = false
}

// 加载搜索模板
const loadSearchTemplate = (template) => {
  if (template.quickSearch) {
    quickSearchText.value = template.quickSearch.text
    quickSearchField.value = template.quickSearch.field || ''
  } else {
    quickSearchText.value = ''
    quickSearchField.value = ''
  }
  
  if (template.conditions && template.conditions.length > 0) {
    searchConditions.value = JSON.parse(JSON.stringify(template.conditions))
    isExpanded.value = true
  } else {
    searchConditions.value = [createEmptyCondition()]
  }
  
  ElMessage.success(`已加载搜索模板: ${template.name}`)
}

// 删除搜索模板
const deleteSearchTemplate = (templateId) => {
  ElMessageBox.confirm('确定要删除这个搜索模板吗？', '确认删除', {
    type: 'warning'
  }).then(() => {
    searchTemplates.value = searchTemplates.value.filter(t => t.id !== templateId)
    localStorage.setItem(`search_templates_${props.tableName}`, JSON.stringify(searchTemplates.value))
    ElMessage.success('搜索模板删除成功')
  }).catch(() => {})
}

// 导出搜索结果
const exportSearchResults = () => {
  emit('export')
}

// 加载保存的数据
const loadSavedData = () => {
  // 加载搜索历史
  const savedHistory = localStorage.getItem(`search_history_${props.tableName}`)
  if (savedHistory) {
    try {
      searchHistory.value = JSON.parse(savedHistory)
    } catch (e) {
      console.error('加载搜索历史失败:', e)
    }
  }
  
  // 加载搜索模板
  const savedTemplates = localStorage.getItem(`search_templates_${props.tableName}`)
  if (savedTemplates) {
    try {
      searchTemplates.value = JSON.parse(savedTemplates)
    } catch (e) {
      console.error('加载搜索模板失败:', e)
    }
  }
}

// 监听表名变化
watch(() => props.tableName, () => {
  resetSearch()
  loadSavedData()
}, { immediate: true })

// 暴露给父组件的方法
defineExpose({
  resetSearch,
  setSearchResult: (count) => {
    searchResultCount.value = count
    hasResults.value = count > 0
  }
})

// 初始化
onMounted(() => {
  loadSavedData()
})
</script>

<style scoped>
.advanced-search {
  margin-bottom: 20px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.search-actions {
  display: flex;
  gap: 8px;
}

.quick-search {
  margin-bottom: 16px;
}

.advanced-conditions {
  border-top: 1px solid #ebeef5;
  padding-top: 16px;
}

.conditions-container {
  margin-bottom: 16px;
}

.condition-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
  padding: 8px;
  background-color: #fafbfc;
  border-radius: 6px;
}

.logic-operator {
  min-width: 80px;
}

.field-select {
  min-width: 140px;
}

.operator-select {
  min-width: 100px;
}

.value-input {
  min-width: 160px;
}

.range-inputs {
  display: flex;
  align-items: center;
  gap: 8px;
}

.range-separator {
  color: #909399;
  font-size: 12px;
}

.condition-actions {
  min-width: 40px;
}

.add-condition {
  margin-bottom: 16px;
}

.search-templates {
  margin-bottom: 16px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.template-title {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 8px;
}

.template-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.template-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.template-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-actions-bottom {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin-bottom: 16px;
}

.search-history {
  padding: 12px;
  background-color: #fafbfc;
  border-radius: 6px;
  border-top: 1px solid #ebeef5;
}

.history-title {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 8px;
}

.history-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.history-tag {
  cursor: pointer;
  opacity: 0.8;
  transition: all 0.3s;
}

.history-tag:hover {
  opacity: 1;
  transform: translateY(-1px);
}

.search-results-info {
  margin-bottom: 16px;
}

.result-summary {
  display: flex;
  gap: 16px;
  font-size: 14px;
  color: #67c23a;
}

@media (max-width: 768px) {
  .condition-row {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
  
  .logic-operator,
  .field-select,
  .operator-select,
  .value-input {
    min-width: auto;
    width: 100%;
  }
  
  .search-actions-bottom {
    flex-direction: column;
  }
  
  .template-list,
  .history-list {
    flex-direction: column;
  }
}
</style>